package dream.dpx.pay.controller;

import dream.dpx.pay.domain.Config;
import dream.dpx.pay.domain.Orders;
import dream.dpx.pay.mapper.ConfigMapper;
import dream.dpx.pay.mapper.OrdersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import zhibi.frame.springmvc.base.AbstractController;
import zhibi.utils.security.SecurityUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.UUID;

@Controller
public class IndexController extends AbstractController {


    private static final String domain = "http://sghfd.biz";
    private static final String customerId = "tYl7OciRXQa0wH23";
    private static final String md5Key = "S7hC3Jtrt8S5kDDSwN32iYJtF9YWJfA7";

    @Autowired
    private ConfigMapper configMapper;
    @Autowired
    private OrdersMapper ordersMapper;

    public static String getIPAddr(HttpServletRequest request) {
        if (request == null)
            return null;
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("Proxy-Client-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("WL-Proxy-Client-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("HTTP_CLIENT_IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            ip = request.getRemoteAddr();
        if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip))
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException unknownhostexception) {
            }
        return ip;
    }

    @RequestMapping({"index", "/"})
    public String index(Model model) {
        Config config = configMapper.selectByPrimaryKey(1);
        model.addAttribute(config);
        return "index";
    }

    /**
     * 商户ID： tYl7OciRXQa0wH23
     * 商户MD5Key： S7hC3Jtrt8S5kDDSwN32iYJtF9YWJfA7
     * <p>
     * 接口地址: https://zf.btc360.io/payment/{商户ID}
     * <p>
     * <p>
     * sign = md5( pickupUrl + receiveUrl + signType + orderNo + orderAmount + ord
     * erCurrency + customerId + md5Key );
     * <p>
     * https://zf.btc360.io/payment/xx?orderNo=xx&customerId=xx&orderCurrency=xx&o
     * rderAmount=xx&receiveUrl=xx&pickupUrl=xx&signType=xx&sign=xx
     */
    @PostMapping("pay")
    public String pay(String name, String user, Double money) {
        Config config = configMapper.selectByPrimaryKey(1);
        Double min = config.getValue();
        if (money != null && money >= min) {
            String orderNo = UUID.randomUUID().toString().replaceAll("-", "");
            String pickupUrl = domain + "/notifyView";
            String receiveUrl = domain + "/notify";
            String signType = "MD5";
            String orderCurrency = "CNY";
            String sign = pickupUrl + receiveUrl + signType + orderNo + money + orderCurrency + name + md5Key;
            logger.info("【签名串】" + sign);
            sign = SecurityUtils.MD5(sign).toLowerCase();
            logger.info("【签名】" + sign);
            String url = "https://zf.btc360.io/payment/" + customerId + "?orderNo=" + orderNo
                    + "&customerId=" + name + "&orderCurrency=" + orderCurrency
                    + "&orderAmount=" + money + "&receiveUrl=" + receiveUrl + "&pickupUrl=" + pickupUrl + "&signType=" + signType
                    + "&sign=" + sign;

            Orders orders = new Orders();
            orders.setAddTime(new Date());
            orders.setMoney(money);
            orders.setId(orderNo);
            orders.setName(name);
            orders.setUser(user);
            orders.setIp(getIPAddr(request));
            orders.setReq(url);
            orders.setStatus("WAIT");
            ordersMapper.insertSelective(orders);

            logger.info("【提交入金】 " + url);
            return redirect(url);
        } else {
            request.setAttribute("html", "至少入金" + min);
        }
        return "pay";
    }


    @RequestMapping("notify")
    @ResponseBody
    public String notify_(String orderNo, String orderAmount, String orderCurrency, String paymentAmount,
                          String transactionId, String status, String signType, String sign) {
        logger.info("【异步通知】 " + orderNo + "  -- " + status);

        String signNew = SecurityUtils.MD5(signType + orderNo + orderAmount + orderCurrency + transactionId + status + md5Key);


        if (signNew.equalsIgnoreCase(sign)) {
            logger.info("【 签名 验证成功】");
            Orders orders = ordersMapper.selectByPrimaryKey(orderNo);
            if(orders != null){
                orders.setStatus(status);
                orders.setResp(signType + orderNo + orderAmount + orderCurrency + transactionId + status + md5Key);
                ordersMapper.updateByPrimaryKeySelective(orders);
                return "success";
            }else{
                logger.info("【异步通知  订单找不到】 " + orderNo + "  -- " + status);
            }
        }
        return "fail";
    }

    @RequestMapping("notifyView")
    public String notifyView() {
        logger.info("【页面通知】 ");

        return "notify";
    }
}
